//
//  ZHomeTableViewController.swift
//  swift-weibo
//
//  Created by zero on 17/3/19.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

private let homeCell = "homeCell"

class ZHomeTableViewController: ZBaseTableViewController {

    var homeControllerViewModel = ZHomeControllerViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(rightClick))
    
        setTableViewAttr()
        
        loadData()
        
    }
    
    //  底部的刷新
    fileprivate lazy var footerView:UIActivityIndicatorView = {
       
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        
        view.color = UIColor.orange
        
        return view
    }()
    
    
    //  顶部的刷新
    fileprivate lazy var zRefreshControl:ZRefreshControl = {
       
        let view = ZRefreshControl()
        
        
        view.addTarget(self, action: #selector(refreshData), for: .valueChanged)
        
        return view
    }()
    
    //  跟新微博的信息
    fileprivate lazy var labNewInfo:UILabel = {
       
        let lab = UILabel(frame: CGRect(x: 0, y: -35, width: UIScreen.main.bounds.size.width, height: 35))
            
        lab.backgroundColor = UIColor.orange
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textAlignment = .center
        lab.isHidden = true
        
        return lab
        
    }()
    
    @objc private func refreshData(){
        
        loadData()
    }
    
    //  界面显示
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        
        self.tableView.reloadData()
    }

    //  设置tableView的属性
    private func setTableViewAttr(){
        
//        self.tableView.rowHeight = 200;
        
        self.tableView.estimatedRowHeight = 200
        self.tableView.rowHeight = UITableViewAutomaticDimension
        
        self.tableView.register(ZHomeTableViewCell.self, forCellReuseIdentifier: homeCell)
        
        //  添加底部刷新
        self.tableView.tableFooterView = footerView
        
        //  添加顶部刷新
        self.tableView.addSubview(zRefreshControl)
        
        //  添加刷新信息
        self.tableView.addSubview(labNewInfo)
        
    }
    
    //  读取数据
    fileprivate func loadData(){
        
        homeControllerViewModel.loadData (isPullUp: footerView.isAnimating){ (res,count) in
            //  停止动画
            
            if self.labNewInfo.isHidden == false{
                
                return
            }
            
            if res {
                
                print("ZHomeTableViewController请求成功")
                self.labNewInfoAnimation(count: count)
                
                self.tableView.reloadData()
            }else{
                
                print("ZHomeTableViewController请求失败")
            }
            
              self.endRefreshing()
        }
    }
    
    
    //  动画
    fileprivate func labNewInfoAnimation(count:Int){
        
        if count == 0 {
            
            labNewInfo.text = "现在已经是最新的微博了"
        }else{
            labNewInfo.text = "已经更新了\(count)条微博"
        }
        
        labNewInfo.isHidden = false
        //  添加动画
        UIView.animate(withDuration: 1, delay: 0.5, options: [], animations: {
            
            self.labNewInfo.transform = CGAffineTransform(translationX: 0, y: 35)
            
        }) { (_) in
            
            UIView.animate(withDuration: 1, animations: {
                
                self.labNewInfo.transform = CGAffineTransform.identity
            }, completion: { (_) in
                
                self.labNewInfo.isHidden = true
            })
        }
        
        
    }
    
    fileprivate func endRefreshing(){

        self.footerView.stopAnimating()
        self.zRefreshControl.endRefreshing()
        
        }
    
    
    
    
    //  测试按钮
    func rightClick() {
        
        let tempVC = ZTempTableViewController()
        
        navigationController?.pushViewController(tempVC, animated: true)
    }
   
}


extension ZHomeTableViewController{
    
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return homeControllerViewModel.dataList.count 
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: homeCell, for: indexPath) as! ZHomeTableViewCell
        
        cell.homeModelViewModel = homeControllerViewModel.dataList[indexPath.row]
        
        cell.selectionStyle = .none
        
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 如果显示的是最后一个cell
        if indexPath.row == homeControllerViewModel.dataList.count - 1 && !footerView.isAnimating{
            // 开启动画
            footerView.startAnimating()
            // 请求数据
            loadData()
        }
    }

}


